package cn.infinite.security.filter;

import cn.infinite.security.configuration.WxConfigurerProperties;
import cn.infinite.security.error.SmsCodeNotFoundException;
import cn.infinite.security.token.WxAuthAuthenticationToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WxCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SPRING_SECURITY_WX_CODE_KEY = "code";

    public WxCodeAuthenticationFilter(WxConfigurerProperties wxConfigurerProperties) {
        super(new AntPathRequestMatcher(wxConfigurerProperties.getAuthenticateCallBackPoint(), "GET"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws
            AuthenticationException, IOException, ServletException {

        String code = request.getParameter(SPRING_SECURITY_WX_CODE_KEY);

        if (StringUtils.isBlank(code)) {
            logger.error("Code不能为空");
            throw new SmsCodeNotFoundException();
        }

        WxAuthAuthenticationToken token = new WxAuthAuthenticationToken(null, code);
        setDetails(request, token);
        return this.getAuthenticationManager().authenticate(token);
    }

    protected void setDetails(HttpServletRequest request,
                              WxAuthAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }


}
